<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目编码" prop="projectCode">
        <el-input
          v-model="queryParams.projectCode"
          placeholder="请输入项目编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属公司" prop="companyId">
        <company-select
          v-model="queryParams.companyId"
          placeholder="请选择所属公司"
          width="240px"
        />
      </el-form-item>
      <el-form-item label="项目状态" prop="projectStatus">
        <el-select v-model="queryParams.projectStatus" placeholder="请选择状态" clearable>
          <el-option label="进行中" value="1" />
          <el-option label="已完成" value="2" />
          <el-option label="已暂停" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pack:project:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pack:project:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pack:project:remove']"
        >删除</el-button>
      </el-col>
      <!-- 暂时隐藏导出功能 -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['pack:project:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column type="index" label="序号" width="60" align="center" />
      
      <el-table-column
        label="项目编码"
        align="left"
        prop="projectCode"
        width="120"
        :show-overflow-tooltip="true"
      />
      
      <el-table-column
        label="项目名称"
        align="left"
        prop="projectName"
        min-width="150"
        :show-overflow-tooltip="true"
      />
      
      <el-table-column
        label="所属公司"
        align="left"
        prop="companyName"
        width="120"
        :show-overflow-tooltip="true"
      />
      
      <el-table-column
        label="器具货主"
        align="left"
        prop="containerOwnerName"
        width="120"
        :show-overflow-tooltip="true"
      />
      
      <el-table-column
        label="物料货主"
        align="left"
        prop="materialOwnerName"
        width="120"
        :show-overflow-tooltip="true"
      />
      
      <el-table-column
        label="业务日期"
        align="center"
        width="180"
      >
        <template slot-scope="scope">
          <div>
            <div>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</div>
            <div class="text-muted" style="font-size: 12px;">
              至 {{ scope.row.endDate ? parseTime(scope.row.endDate, '{y}-{m}-{d}') : '长期' }}
            </div>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column label="项目状态" align="center" width="80">
        <template slot-scope="scope">
          <el-tag 
            :type="getStatusType(scope.row.projectStatus)"
            size="mini"
          >
            {{ getStatusText(scope.row.projectStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column
        label="统计信息"
        align="center"
        width="120"
      >
        <template slot-scope="scope">
          <div>
            <el-tag size="mini" type="info">物料: {{ scope.row.materialCount || 0 }}</el-tag>
            <br>
            <el-tag size="mini" type="warning" style="margin-top: 2px;">
              仓库: {{ scope.row.warehouseCount || 0 }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="120"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      
      <el-table-column
        label="操作"
        align="center"
        width="180"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['pack:project:query']"
          >详情</el-button>
          
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pack:project:edit']"
          >修改</el-button>
          
          <el-dropdown
            @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="['pack:project:material', 'pack:project:warehouse', 'pack:project:remove']"
          >
            <el-button size="mini" type="text">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item 
                command="material" 
                icon="el-icon-goods"
                v-hasPermi="['pack:project:material']"
              >物料管理</el-dropdown-item>
              <el-dropdown-item 
                command="warehouse" 
                icon="el-icon-office-building"
                v-hasPermi="['pack:project:warehouse']"
              >仓库权限</el-dropdown-item>
              <el-dropdown-item 
                command="delete" 
                icon="el-icon-delete"
                v-hasPermi="['pack:project:remove']"
              >删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/修改抽屉 -->
    <el-drawer
      :title="title"
      :visible.sync="open"
      direction="rtl"
      size="800px"
      :before-close="cancel"
    >
      <div style="padding: 20px;">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-tabs v-model="activeTab" type="border-card">
            <!-- 基本信息 -->
            <el-tab-pane label="基本信息" name="basic">
              <basic-info-form 
                ref="basicInfoForm"
                :form="form" 
                :rules="rules"
                @company-change="handleCompanyChange"
                @container-owner-change="handleContainerOwnerChange"
                @material-owner-change="handleMaterialOwnerChange"
              />
            </el-tab-pane>
            
            <!-- 物料配置 -->
            <el-tab-pane label="物料配置" name="material">
              <material-config-form
                ref="materialConfigForm"
                :material-list="form.materialList"
                :material-operations="form.materialOperations"
                :is-edit="form.projectId != null"
                @add-material="handleAddMaterial"
                @edit-material="handleEditMaterial"
                @delete-material="handleDeleteMaterial"
              />
            </el-tab-pane>
            
            <!-- 仓库权限 -->
            <el-tab-pane label="仓库权限" name="warehouse">
              <warehouse-permission-form
                ref="warehousePermissionForm"
                :warehouse-list="form.warehouseOperationList"
                :warehouse-operations="form.warehouseOperations"
                :is-edit="form.projectId != null"
                :warehouse-options="warehouseOptions"
                @add-warehouse="handleAddWarehouse"
                @edit-warehouse="handleEditWarehouse"
                @delete-warehouse="handleDeleteWarehouse"
              />
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </div>
      
      <div style="padding: 20px; text-align: right; border-top: 1px solid #e8e8e8;">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
      </div>
    </el-drawer>

    <!-- 详情抽屉 -->
    <el-drawer
      title="项目详情"
      :visible.sync="detailOpen"
      direction="rtl"
      size="800px"
    >
      <div style="padding: 20px;">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="项目编码">{{ detailForm.projectCode }}</el-descriptions-item>
          <el-descriptions-item label="项目名称">{{ detailForm.projectName }}</el-descriptions-item>
          <el-descriptions-item label="所属公司">{{ detailForm.companyName }}</el-descriptions-item>
          <el-descriptions-item label="器具货主">{{ detailForm.containerOwnerName }}</el-descriptions-item>
          <el-descriptions-item label="物料货主">{{ detailForm.materialOwnerName }}</el-descriptions-item>
          <el-descriptions-item label="业务起始日期">{{ detailForm.startDate }}</el-descriptions-item>
          <el-descriptions-item label="业务结束日期">{{ detailForm.endDate || '长期' }}</el-descriptions-item>
          <el-descriptions-item label="项目状态">
            <el-tag :type="getStatusType(detailForm.projectStatus)">
              {{ getStatusText(detailForm.projectStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ detailForm.remark }}</el-descriptions-item>
        </el-descriptions>
        
        <!-- 物料配置 -->
        <el-divider content-position="left">物料配置</el-divider>
        <el-table :data="detailForm.materialList" size="small" border>
          <el-table-column label="物料编码" prop="materialCode" width="120" />
          <el-table-column label="物料名称" prop="materialName" min-width="150" />
          <el-table-column label="器具型号" prop="containerMaterialCode" width="120" />
          <el-table-column label="收容数" prop="capacityCount" width="80" align="center" />
          <el-table-column label="体积(m³)" prop="volume" width="100" align="center" />
          <el-table-column label="重量(kg)" prop="weight" width="100" align="center" />
          <el-table-column label="货值(元)" prop="goodsValue" width="120" align="center" />
        </el-table>
        
        <!-- 仓库权限 -->
        <el-divider content-position="left">仓库权限</el-divider>
        <el-table :data="detailForm.warehouseOperationList" size="small" border>
          <el-table-column label="仓库名称" prop="warehouseName" min-width="150" />
          <el-table-column label="满箱入库" width="80" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.allowFullInbound === '1' ? 'success' : 'danger'" size="mini">
                {{ scope.row.allowFullInbound === '1' ? '允许' : '禁止' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="满箱出库" width="80" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.allowFullOutbound === '1' ? 'success' : 'danger'" size="mini">
                {{ scope.row.allowFullOutbound === '1' ? '允许' : '禁止' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="装箱权限" width="80" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.allowPacking === '1' ? 'success' : 'danger'" size="mini">
                {{ scope.row.allowPacking === '1' ? '允许' : '禁止' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="拆箱权限" width="80" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.allowUnpacking === '1' ? 'success' : 'danger'" size="mini">
                {{ scope.row.allowUnpacking === '1' ? '允许' : '禁止' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { 
  listProject, 
  getProject, 
  delProject, 
  addProject, 
  updateProject, 
  exportProject,
  delProjectEnhanced
} from "@/api/pack/project";
import { listWarehouse } from "@/api/pack/warehouse";
import BasicInfoForm from './components/BasicInfoForm.vue';
import MaterialConfigForm from './components/MaterialConfigForm.vue';
import WarehousePermissionForm from './components/WarehousePermissionForm.vue';

export default {
  name: "Project",
  components: {
    BasicInfoForm,
    MaterialConfigForm,
    WarehousePermissionForm
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情
      detailOpen: false,
      // 提交加载状态
      submitLoading: false,
      // 当前活跃标签页
      activeTab: 'basic',
      // 仓库选项
      warehouseOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectCode: null,
        projectName: null,
        companyId: null,
        projectStatus: null
      },
      // 表单参数
      form: {
        projectId: null,
        projectCode: null,
        projectName: null,
        companyId: null,
        containerOwnerId: null,
        materialOwnerId: null,
        startDate: null,
        endDate: null,
        projectStatus: "1",
        remark: null,
        materialList: [],
        warehouseOperationList: [],
        materialOperations: [],
        warehouseOperations: []
      },
      // 详情表单
      detailForm: {},
      // 表单校验
      rules: {
        projectCode: [
          { required: true, message: "项目编码不能为空", trigger: "blur" },
          { min: 1, max: 50, message: "项目编码长度在1到50个字符", trigger: "blur" },
          { pattern: /^[A-Z0-9]+$/, message: "项目编码只能包含大写字母和数字", trigger: "blur" }
        ],
        projectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" },
          { min: 1, max: 100, message: "项目名称长度在1到100个字符", trigger: "blur" }
        ],
        companyId: [
          { required: true, message: "所属公司不能为空", trigger: "change" }
        ],
        containerOwnerId: [
          { required: true, message: "器具货主不能为空", trigger: "change" }
        ],
        materialOwnerId: [
          { required: true, message: "物料货主不能为空", trigger: "change" }
        ],
        startDate: [
          { required: true, message: "业务起始日期不能为空", trigger: "change" }
        ],
        endDate: [
          { 
            validator: (rule, value, callback) => {
              if (value && this.form.startDate && new Date(value) <= new Date(this.form.startDate)) {
                callback(new Error('结束日期必须晚于起始日期'));
              } else {
                callback();
              }
            }, 
            trigger: "change" 
          }
        ],
        projectStatus: [
          { required: true, message: "项目状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getWarehouseOptions();
  },
  methods: {
    /** 查询项目列表 */
    getList() {
      this.loading = true;
      listProject(this.queryParams).then(response => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 获取仓库选项 */
    getWarehouseOptions() {
      listWarehouse({}).then(response => {
        this.warehouseOptions = response.rows || [];
      });
    },
    /** 项目状态类型 */
    getStatusType(status) {
      const statusMap = {
        '1': 'success',  // 进行中
        '2': 'info',     // 已完成
        '3': 'warning'   // 已暂停
      };
      return statusMap[status] || 'info';
    },
    /** 项目状态文本 */
    getStatusText(status) {
      const statusMap = {
        '1': '进行中',
        '2': '已完成',
        '3': '已暂停'
      };
      return statusMap[status] || '未知';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: null,
        projectCode: null,
        projectName: null,
        companyId: null,
        containerOwnerId: null,
        materialOwnerId: null,
        startDate: null,
        endDate: null,
        projectStatus: "1",
        remark: null,
        materialList: [],
        warehouseOperationList: [],
        materialOperations: [],
        warehouseOperations: []
      };
      this.resetForm("form");
      this.activeTab = 'basic';
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.projectId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const projectId = row.projectId || this.ids[0];
      getProject(projectId).then(response => {
        // 确保数据结构完整
        this.form = {
          ...response.data,
          materialList: response.data.materialList || [],
          warehouseOperationList: response.data.warehouseOperationList || [],
          materialOperations: [],
          warehouseOperations: []
        };
        this.open = true;
        this.title = "修改项目";
        
        // 添加调试信息
        console.log('项目数据加载完成:', this.form);
        console.log('物料列表:', this.form.materialList);
        console.log('仓库权限列表:', this.form.warehouseOperationList);
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      const projectId = row.projectId;
      getProject(projectId).then(response => {
        this.detailForm = response.data;
        this.detailOpen = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.submitLoading = true;
          
          // 检查是否有物料或仓库权限配置
          const hasDetails = (this.form.materialList && this.form.materialList.length > 0) ||
                            (this.form.warehouseOperationList && this.form.warehouseOperationList.length > 0);
          
          if (this.form.projectId != null) {
            // 修改项目
            const hasOperations = (this.form.materialOperations && this.form.materialOperations.length > 0) ||
                                 (this.form.warehouseOperations && this.form.warehouseOperations.length > 0);
            
            updateProject(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              
              // 显示操作结果
              if (hasOperations && response.data) {
                this.showOperationResults(response.data);
              }
            }).finally(() => {
              this.submitLoading = false;
            });
          } else {
            // 新增项目
            addProject(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              
              // 显示创建结果
              if (hasDetails && response.data) {
                this.showCreateResults(response.data);
              }
            }).finally(() => {
              this.submitLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const projectIds = row.projectId || this.ids;
      const projectCodes = [];
      
      if (row.projectId) {
        projectCodes.push(row.projectCode);
      } else {
        this.ids.forEach(id => {
          const project = this.projectList.find(p => p.projectId === id);
          if (project) {
            projectCodes.push(project.projectCode);
          }
        });
      }
      
      this.$modal.confirm('是否确认删除项目编码为"' + projectCodes.join(', ') + '"的数据项？')
        .then(() => {
          return delProject(projectIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pack/project/export', {
        ...this.queryParams
      }, `project_${new Date().getTime()}.xlsx`)
    },
    /** 下拉菜单命令处理 */
    handleCommand(command, row) {
      switch (command) {
        case 'material':
          this.handleMaterialManagement(row);
          break;
        case 'warehouse':
          this.handleWarehouseManagement(row);
          break;
        case 'delete':
          this.handleDelete(row);
          break;
      }
    },
    /** 物料管理 */
    handleMaterialManagement(row) {
      this.handleUpdate(row);
      this.$nextTick(() => {
        this.activeTab = 'material';
      });
    },
    /** 仓库权限管理 */
    handleWarehouseManagement(row) {
      this.handleUpdate(row);
      this.$nextTick(() => {
        this.activeTab = 'warehouse';
      });
    },
    /** 公司变更处理 */
    handleCompanyChange(company) {
      // 公司变更时可以执行相关逻辑
      console.log('所属公司变更:', company);
    },
    /** 器具货主变更处理 */
    handleContainerOwnerChange(company) {
      console.log('器具货主变更:', company);
    },
    /** 物料货主变更处理 */
    handleMaterialOwnerChange(company) {
      console.log('物料货主变更:', company);
    },
    /** 物料相关操作 */
    handleAddMaterial() {
      // 由子组件处理
      this.activeTab = 'material';
    },
    handleEditMaterial(material) {
      // 由子组件处理
      console.log('编辑物料:', material);
    },
    handleDeleteMaterial(material) {
      // 由子组件处理
      console.log('删除物料:', material);
    },
    /** 仓库权限相关操作 */
    handleAddWarehouse() {
      // 由子组件处理
      this.activeTab = 'warehouse';
    },
    handleEditWarehouse(warehouse) {
      // 由子组件处理
      console.log('编辑仓库权限:', warehouse);
    },
    handleDeleteWarehouse(warehouse) {
      // 由子组件处理
      console.log('删除仓库权限:', warehouse);
    },
    /** 显示操作结果 */
    showOperationResults(data) {
      let message = `项目修改成功！<br/>`;
      
      if (data.materialOperationResults) {
        message += `<br/><strong>物料操作结果：</strong><br/>`;
        data.materialOperationResults.forEach(result => {
          const icon = result.success ? '✅' : '❌';
          message += `${icon} ${result.operationType}: ${result.message}<br/>`;
        });
      }
      
      if (data.warehouseOperationResults) {
        message += `<br/><strong>仓库权限操作结果：</strong><br/>`;
        data.warehouseOperationResults.forEach(result => {
          const icon = result.success ? '✅' : '❌';
          message += `${icon} ${result.operationType}: ${result.message}<br/>`;
        });
      }
      
      this.$alert(message, '操作结果', {
        dangerouslyUseHTMLString: true,
        type: 'info'
      });
    },
    /** 显示创建结果 */
    showCreateResults(data) {
      let message = `项目创建成功！<br/>`;
      message += `项目ID: ${data.projectId}<br/>`;
      message += `项目编码: ${data.projectCode}<br/>`;
      
      if (data.materialCount > 0) {
        message += `物料配置: ${data.materialCount}个<br/>`;
      }
      
      if (data.warehouseOperationCount > 0) {
        message += `仓库权限配置: ${data.warehouseOperationCount}个<br/>`;
      }
      
      this.$alert(message, '创建结果', {
        dangerouslyUseHTMLString: true,
        type: 'success'
      });
    }
  }
};
</script>

<style scoped>
.text-muted {
  color: #999;
}
</style> 